// 云函数/userLogin/index.js
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const users = db.collection('bx_user')

exports.main = async (event, context) => {

  const { code, userInfo } = event
  
  console.log(userInfo);
  console.log(code);

  // 1. 获取微信上下文
  const { OPENID, APPID, UNIONID } = cloud.getWXContext()
  
  try {
    // 2. 查询用户是否存在
    const { data } = await users.where({ _openid: OPENID }).get()
    
    // 3. 用户不存在则创建
    if (data.length === 0) {
      await users.add({
        data: {
          _openid: OPENID,
          unionid: UNIONID,
          ...userInfo,
          createdAt: db.serverDate(),
          lastLogin: db.serverDate(),
          status: 'active'
        }
      })
    } else {
      // 4. 用户存在则更新信息
      await users.where({ _openid: OPENID }).update({
        data: {
          ...userInfo,
          lastLogin: db.serverDate()
        }
      })
    }
    
    return {
      code: 200,
      openid: OPENID,
      userInfo,
      isNewUser: data.length === 0
    }
  } catch (err) {
    console.error('云函数错误:', err)
    return {
      code: 500,
      message: '服务器错误'
    }
  }
}